package main

import (
	"fmt"
	"os"
	"server/src/protocol808"
	"strconv"
	//"smartu365.com/protocol808"
)

func BlankResponse(msgType string, terminalId string) string {
	var serialNo uint16 = 1

	res := protocol808.Response{}
	res.MessageType = protocol808.PTGetProperty
	res.SerialNo = serialNo
	res.TerminalId = terminalId
	response := res.Pack()

	return response
}

func testRemoteUpdate() {
	ru := protocol808.RemoteUpdate{}
	ru.TerminalId = "030319330107"
	ru.SerialNo = 1
	ru.Productor = "SZRXT"
	ru.Url = "http://extra.smartu365.com/update/V1.0.5.vxp"
	ru.FirmwareVersion = "RXTmt2503aeV20"
	ru.SoftwareVersion = "203V1.0.5"

	fmt.Println(ru.Pack())
}

func str2Hex(str string) int {
	if str == "" {
		return 0
	}
	i, err := strconv.ParseInt(str, 16, 0)
	if err != nil {
		return 0
	} else {
		return int(i)
	}
}

func sum(text string) uint8 {
	if text == "" {
		return 0
	}
	var res uint8
	var sTemp string
	var iTemp int

	for i := 0; i < len(text); i += 2 {
		sTemp = text[i : i+2]
		iTemp = str2Hex(sTemp)
		if i == 0 {
			res = uint8(iTemp)
		} else {
			res ^= uint8(iTemp)
		}
	}
	return res
}

func tranfer(str string) string {
	for i := len(str) - 2; i >= 0; i -= 2 {
		if str[i] == '7' {
			if str[i+1] == 'E' {
				str = str[:i] + "7D02" + str[i+2:]
			} else if str[i+1] == 'D' {
				str = str[:i] + "7D01" + str[i+2:]
			}
		}
	}

	return str
}

func int2HexStr(val int, format string) string {
	return fmt.Sprintf(format, val)
}

func main() {
	sText := os.Args[1]
	fmt.Println("原始数据：", sText)

	pro808 := protocol808.Request{}
	err, header, body := pro808.Parse(sText)

	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("消息ID：\t%s(%s)\n", header.MessageType, header.MessageTypeCH)
	fmt.Printf("终端ID：\t%s\n", header.TerminalId)
	fmt.Printf("消息流水号：\t%s\n", header.MessageSerialNumber)
	fmt.Printf("消息体属性：\t%s\n", header.MessageAttribute)
	fmt.Printf("校验码:\t%s\n", header.CheckCode)
	fmt.Printf("消息内容:\t%s\n", body)
	fmt.Println("-----------------------------------------------")
	switch header.MessageType {
	case protocol808.PTRegister:
		{
			register := protocol808.Register{}
			register.Set(body)
			fmt.Printf("IMEI:\t%s\n", register.IMEI)
		}
	case protocol808.PTAuthentication:
		{
			auth := protocol808.Authentication{}
			auth.Set(body)
			auth.Out()
		}
	case protocol808.PTPosition:
		{
			position := protocol808.TerminalPosition{}
			position.Set(body)
			position.Out()
		}
	case protocol808.PTTirePresure:
		{
			tirePressure := protocol808.TirePressure{}
			tirePressure.Set(body)
			tirePressure.Out()
		}
	case protocol808.PTAnswerProperty:
		{
			answerProperty := protocol808.AnswerProperty{}
			answerProperty.Set(body)
			answerProperty.Out()
		}
	case protocol808.PTAnswerParameter:
		{
			answerPramater := protocol808.AnswerParamenter{}
			answerPramater.Set(body)
			answerPramater.Out()
		}
	}
}
